<?php

namespace App\Http\Controllers;

use App\Writing;
use App\WritingComment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WritingCommentController extends Controller
{
    public function post_index(Request $request){//得到评论列表
        $writing= WritingComment::with(['user','replay_user'])
            ->where('writing_id',$request->id)
            ->where('is_display',1)
            ->orderBy('id','desc')
            ->get();

        return $this->send_message('success',$writing);

    }
    public function post_comment(Request $request){//写进一条评论
        $author=Auth::user();
        $replay_user_id=$request->replay_user_id ? $request->replay_user_id : null;
        $this->validate($request,[
           'content'=>'required',
            'writing_id'=>'required',
        ]);

        //判断是否有评论权限
        if($author->allow_comment==0){
            return $this->send_message('error',trans('web.comment_permission'));
        }
        //写入评论
        $comment=new WritingComment();
        $comment->content=$request->input('content');
        $comment->author_id=$author->id;
        $comment->replay_user_id=$replay_user_id;
        $comment->writing_id=$request->writing_id;
        $comment->save();
        $comments=WritingComment::with(['user','replay_user'])->find($comment->id);
        $writing=Writing::find($comments->writing_id);
        $writing->increment('comments',1);
        return $this->send_message('success',$comments);

    }
    public function display_comment(Request $request){//屏蔽评论
        $comment=WritingComment::findOrFail($request->id);
        $comment->is_display=0;
        $comment->save();
        $writing=Writing::find($comment->writing_id);
        $writing->decrement('comments',1);
        return $this->send_message('success',trans('web.displayed'));

    }
    protected function send_message($status,$message){
        return [
            'status'=>$status,
            'message'=>$message
        ];
    }
}
